package dao

import (
	"errors"
	"github.com/wonderivan/logger"
	"gorm.io/gorm"
	"ruoyi-go/app/admin/entity"
	"ruoyi-go/app/admin/model/tools"
	"ruoyi-go/pkg/mysql"
	"ruoyi-go/utils"
	"ruoyi-go/utils/R"
	"time"
)

// InRecordsSave 创建
func InRecordsSave(req entity.InRecords) R.Result {
	req.CreateTime = &utils.JsonTime{Time: time.Now()}
	req.UpdateTime = &utils.JsonTime{Time: time.Now()}

	err := mysql.MysqlDb().Create(&req).Error
	if err != nil {
		logger.Error(err)
		return R.ReturnFailMsg("保存失败")
	}
	return R.ReturnSuccess(nil)
}

// InRecordPage 分页查询
func InRecordPage(req entity.InRecordsPageReq) tools.TableDataInfo {
	db := mysql.MysqlDb().Model(&entity.InRecords{})
	println(req.InScaleTimeBegin)
	println(&req.InScaleTimeBegin)
	if req.InScaleTimeBegin != nil && !req.InScaleTimeBegin.IsZero() {
		db.Where("in_scale_time >= ?", req.InScaleTimeBegin)
	}
	if req.InScaleTimeEnd != nil && !req.InScaleTimeEnd.IsZero() {
		db.Where("in_scale_time <= ?", req.InScaleTimeEnd)
	}
	if req.PlateNumber != "" {
		db.Where("plate_number like ?", "%"+req.PlateNumber+"%")
	}
	if req.OrderMatch == 1 {
		db = db.Where("order_id IS NOT NULL")
	} else if req.OrderMatch == 2 {
		db = db.Where("order_id IS NULL")
	}
	if req.OutScaleTimeBegin != nil && !req.OutScaleTimeBegin.IsZero() {
		db.Where("out_scale_time >= ?", req.OutScaleTimeBegin)
	}
	if req.OutScaleTimeEnd != nil && !req.OutScaleTimeEnd.IsZero() {
		db.Where("out_scale_time <= ?", req.OutScaleTimeEnd)
	}
	// 分页参数处理
	page := req.Current
	pageSize := req.Size

	// 计算偏移量
	offset := (page - 1) * pageSize
	// 获取总数
	var total int64
	if err := db.Count(&total).Error; err != nil {
		logger.Error("分页查询总数失败: ", err)
		return tools.Fail()
	}

	// 查询列表数据
	var list []entity.InRecords
	if err := db.Offset(offset).Limit(pageSize).Order("create_time desc").Find(&list).Error; err != nil {
		logger.Error("分页查询数据失败: ", err)
		return tools.Fail()
	}
	return tools.Success(list, total)
}

func InRecordsDelete(ids string) interface{} {
	if len(ids) == 0 {
		return R.ReturnFailMsg("参数获取失败")
	}
	err := mysql.MysqlDb().Delete(&entity.InRecords{}, "id in (?)", ids).Error
	if err != nil {
		return R.ReturnFailMsg("批量删除失败")
	}
	return R.ReturnSuccess(nil)
}

func GetInRecordsById(id string) interface{} {
	if id == "" {
		return R.ReturnFailMsg("参数获取失败")
	}
	var data entity.InRecords
	if err := mysql.MysqlDb().Find(&data, id).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return R.ReturnFailMsg("找不到该条入场记录")
		}
		return R.ReturnFailMsg("获取数据失败")
	}
	return R.ReturnSuccess(data)
}
